package com.fast.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 通用工具类
 *
 * @author ylc 2017年2月13日15:14:53
 */
public class CommonUtil {
    protected static Logger logger = LoggerFactory.getLogger(CommonUtil.class);

    public static String formatDateTime(Date date, Time time) {
        DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat timeFormatter = new SimpleDateFormat("HH:mm:ss");
        return dateFormatter.format(date) + " " + timeFormatter.format(time);
    }

    public static String formatShortDateTime(Date date, Time time) {
        DateFormat dateShortFormatter = new SimpleDateFormat("yyyy-M-d");
        DateFormat timeShortFormatter = new SimpleDateFormat("H:m:s");
        return dateShortFormatter.format(date) + " " + timeShortFormatter.format(time);
    }

    public static String formatDate(Date date) {
        DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormatter.format(date);
    }

    public static String formatFullDate(Date date) {
        DateFormat fullDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return fullDateFormatter.format(date);
    }

    public static String getFullDateTag() {
        DateFormat fullDateFormatterForTag = new SimpleDateFormat("yyyyMMddHHmmss");
        return fullDateFormatterForTag.format(Calendar.getInstance().getTime());
    }

    public static String getMinuteDate() {
        DateFormat fullDateFormatterForTag = new SimpleDateFormat("yyyyMMddHHmm");
        return fullDateFormatterForTag.format(Calendar.getInstance().getTime());
    }

    public static Date getFullDate(String fullDate) {
        try {
            DateFormat fullDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return fullDateFormatter.parse(fullDate);
        } catch (ParseException e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    public static Date combineDateTime(Date date, Time time) {
        try {
            DateFormat fullDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return fullDateFormatter.parse(formatDateTime(date, time));
        } catch (ParseException e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * 获取当前日期转换成数字（2015-07-08------->20150708）
     *
     * @return
     */
    public static int getDateToInt() {
        Calendar calendar = Calendar.getInstance();
        int dateNO = calendar.get(Calendar.YEAR) * 10000;
        dateNO += (calendar.get(Calendar.MONTH) + 1) * 100;
        dateNO += calendar.get(Calendar.DAY_OF_MONTH);
        return dateNO;
    }

    /**
     * 获取当前日期时间转换成数字（2015-07-08 12:23:34------->20150708122334）
     *
     * @return
     */
    public static long getDateTimeTolong() {
        Calendar calendar = Calendar.getInstance();
        //long dateTime=new BigDecimal(calendar.get(Calendar.YEAR));
        long dateTime = calendar.get(Calendar.YEAR) * 10000000000l;
        dateTime += (calendar.get(Calendar.MONTH) + 1) * 100000000;
        dateTime += calendar.get(Calendar.DAY_OF_MONTH) * 1000000;
        dateTime += calendar.get(Calendar.HOUR_OF_DAY) * 10000;
        dateTime += calendar.get(Calendar.MINUTE) * 100;
        dateTime += calendar.get(Calendar.SECOND);
        return dateTime;
    }

    public static StringBuffer replace(StringBuffer currContent, String orgContent, String newContent) {
        int startIndex = currContent.indexOf(orgContent);
        while (startIndex > 0) {
            currContent.replace(startIndex, startIndex + orgContent.length(), newContent);
            startIndex = currContent.indexOf(orgContent);
        }
        return currContent;
    }

    public static String trim(String value) {
        if (value == null) {
            return null;
        }
        return value.trim().replaceAll("\\\r\\\n", "");
    }

    /**
     * @param proper
     * @return boolean
     * @Description: 判断属性是否为空
     * @Title: properISNULL
     */
    public static boolean properIsNULL(String proper) {
        if (proper == null || "".equals(proper.trim())) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean properIsNULL(Integer proper) {
        if (proper == null || proper <= 0) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean properIsNULL(Long proper) {
        if (proper == null || proper <= 0) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean properIsNULL(Boolean proper) {
        if (proper == null) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean properIsNULL(BigDecimal proper) {
        if (proper == null || proper.equals(BigDecimal.ZERO)) {
            return true;
        } else {
            return false;
        }
    }

    public static <T> boolean properIsNULL(List<T> proper) {
        if (proper == null || proper.size() <= 0) {
            return true;
        } else {
            return false;
        }
    }

    public static String properEncoding(String proper) {
        try {
            proper = new String(proper.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return proper;
    }

    /**
     * 格式化BigDecimal
     *
     * @param val          需要转换的值
     * @param newScale     规模需精确到多少为小数点
     * @param roundingMode 舍入模式
     * @return
     */
    public static BigDecimal formatBigDecimal(String val, int newScale, int roundingMode) {
        BigDecimal bigDecimal = new BigDecimal(val);
        return bigDecimal.setScale(newScale, roundingMode);
    }

    /**
     * 格式化BigDecimal
     *
     * @param bigDecimal   需要转换的值
     * @param newScale     规模需精确到多少为小数点
     * @param roundingMode 舍入模式
     * @return
     */
    public static BigDecimal formatBigDecimal(BigDecimal bigDecimal, int newScale, int roundingMode) {
        return bigDecimal.setScale(newScale, roundingMode);
    }

    /**
     * 是否为空
     *
     * @return
     */
    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        } else if (obj instanceof String) {
            String instance = (String) obj;
            if (instance.trim().length() <= 0 || "null".equalsIgnoreCase(instance)) {
                return true;
            }
        } else if (obj instanceof Integer) {
            Integer instance = (Integer) obj;
            if (instance < 0) {
                return true;
            }
        } else if (obj instanceof List<?>) {
            List<?> instance = (List<?>) obj;
            if (instance.size() <= 0) {
                return true;
            }
        } else if (obj instanceof Map<?, ?>) {
            Map<?, ?> instance = (Map<?, ?>) obj;
            if (instance.size() <= 0) {
                return true;
            }
        } else if (obj instanceof Object[]) {
            Object[] instance = (Object[]) obj;
            if (instance.length <= 0) {
                return true;
            }
        } else if (obj instanceof Long) {
            Long instance = (Long) obj;
            if (instance < 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 驼峰转换为下划线
     *
     * @param camelCaseName
     * @param smallUnderline 是否小写下划线
     * @return
     */
    public static String humpToUnderline(String camelCaseName, boolean smallUnderline) {
        StringBuilder result = new StringBuilder();
        if (camelCaseName != null && camelCaseName.length() > 0) {
            result.append(camelCaseName.substring(0, 1).toLowerCase());
            for (int i = 1; i < camelCaseName.length(); i++) {
                char ch = camelCaseName.charAt(i);
                if (Character.isUpperCase(ch)) {
                    result.append("_");
                    result.append(Character.toLowerCase(ch));
                } else {
                    result.append(ch);
                }
            }
        }
        return smallUnderline == true ? result.toString().toLowerCase() : result.toString().toUpperCase();
    }

    /**
     * 下划线转驼峰法
     *
     * @param line       源字符串
     * @param smallCamel 大小驼峰,是否为小驼峰
     * @return 转换后的字符串
     */
    public static String underlineToHump(String line, boolean smallCamel) {
        if (line == null || "".equals(line)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        Pattern pattern = Pattern.compile("([A-Za-z\\d]+)(_)?");
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(smallCamel && matcher.start() == 0 ? Character.toLowerCase(word.charAt(0)) : Character.toUpperCase(word.charAt(0)));
            int index = word.lastIndexOf('_');
            if (index > 0) {
                sb.append(word.substring(1, index).toLowerCase());
            } else {
                sb.append(word.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }

    /**\
     * 生成订单号
     * @return
     */
    public static String createOrderNum() {
       return String.valueOf(getDateTimeTolong()) +  Math.round( Math.random() * 10000000000L );
    }

    public static void main(String[] args) {

       //  System.out.println(humpToUnderline("userName", false));
        System.out.println( Math.round( Math.random() * 10000000000L ) );
    }
}
